package org.jvm.util;

/**
 * author : 海燕
 * date : 2023/1/14
 * desc :读取byte数组工具
 */
public class ByteArrayReader {

    protected byte[] data;
    protected int count = 0;

    public ByteArrayReader(byte[] data) {
        this.data = data;
    }

    private byte readByte() {
        return this.data[count++];
    }

    /**
     * 将byte视为无符号读出
     *
     * @return
     */
    public int readUint8() {
        return readByte() & 0x0FF;
    }

    /**
     * 将byte视为有符号读出
     *
     * @return
     */
    public int readInt8() {
        return readByte();
    }

    private short readShort() {
        short res = 0;
        for (int i = 0; i < 2; i++) {
            res = (short) (res << 8);
            res ^= readUint8();
        }
        return res;
    }

    public int readInt16() {
        return readShort();
    }

    public int readUint16() {
        return readShort() & 0x0FFFF;
    }

    public int readUint32() {
        int res = 0;
        for (int i = 0; i < 4; i++) {
            res = res << 8;
            res ^= readUint8();
        }
        return res;
    }

    public long readUint64() {
        long res = 0;
        for (int i = 0; i < 8; i++) {
            res = res << 8;
            res ^= readUint8();
        }
        return res;
    }

    /**
     * 先读一个short，根据读出的值n。再连续读n个short作为返回值。
     *
     * @return
     */
    public int[] readUint16s() {
        int n = readUint16();
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = readUint16();
        }
        return res;
    }

    /**
     * 读取指定数量的整形
     *
     * @param n
     * @return
     */
    public int[] readUint32s(int n) {
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = readUint32();
        }
        return res;
    }

    /**
     * 读取指定数量的字节
     *
     * @param n
     * @return
     */
    public byte[] readBytes(int n) {
        byte[] res = new byte[n];
        for (int i = 0; i < n; i++) {
            res[i] = readByte();
        }
        return res;
    }

}